package com.zzedu.web.controller;

import com.alibaba.fastjson.JSON;
import com.zzedu.common.annotation.Log;
import com.zzedu.common.constant.Constants;
import com.zzedu.common.enums.*;
import com.zzedu.common.utils.MessageUtils;
import com.zzedu.common.utils.SecurityUtils;
import com.zzedu.common.utils.ServletUtils;
import com.zzedu.common.utils.StringUtils;
import com.zzedu.framework.manager.factory.AsyncFactory;
import com.zzedu.framework.web.domain.LoginForm;
import com.zzedu.manager.IZzStudentManager;
import com.zzedu.result.Result;
import com.zzedu.result.ResultEnum;
import com.zzedu.stu.req.Login;
import com.zzedu.stu.req.UpdatePwd;
import com.zzedu.stu.rsp.ApiLoginVO;
import com.zzedu.system.service.ISysLogininforService;
import com.zzedu.utils.BaseReq;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * 登录验证
 *
 * @author smarthome
 */
@RestController
public class LoginController {
    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    ISysLogininforService logininforService;

    @Autowired
    IZzStudentManager zzStudentManager;
    /**
     * 登录方法
     *
     * @param loginFormMono
     * @param exchange
     * @return
     */
    @PostMapping(value = {"/login"}, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE})
    public Result<ApiLoginVO> login(@Validated @RequestBody BaseReq<Login> loginBaseReq) {
        Result<ApiLoginVO> result = new Result<>();
        try {
            Login login = loginBaseReq.getData();
            LoginForm loginForm = new LoginForm();
            LoginType loginType = login.getPwdType();
            if (null == loginType) {
                loginType = LoginType.PWD;
            }
            loginForm.setLoginType(loginType);
            loginForm.setPlatformLoginEnumns(PlatformLoginEnumns.WEB_APP);
            loginForm.setPassword(login.getPassWord());
            loginForm.setUsername(login.getUserName());
            loginForm.setUserTypeEnumns(UserTypeEnumns.STUDENT);
            UsernamePasswordAuthenticationToken token =
                    new UsernamePasswordAuthenticationToken(JSON.toJSONString(loginForm), login.getPassWord());
            Authentication authentication = authenticationManager.authenticate(token);
            SecurityContext securityContext = SecurityContextHolder.getContext();
            securityContext.setAuthentication(authentication);
            ServletUtils.getRequest().getSession(true).setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, securityContext);
            AsyncFactory.recordLogininfor(SecurityUtils.getLoginName(), Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"));
            ApiLoginVO data = new ApiLoginVO();
            result.setResultMessage(ResultEnum.SUCCESS.getDesc());
            result.setResultCode(ResultEnum.SUCCESS.getCode());
            data.setToken(ServletUtils.getSession().getId());


            result.setData(data);
            return result;
        } catch (Exception e) {
            String msg = "用户或密码错误";
            if (StringUtils.isNotEmpty(e.getMessage())) {
                msg = e.getMessage();
            }
            result.setResultMessage(msg);
            result.setResultCode(ResultEnum.FAIL.getCode());
            return result;
        }
    }

    /**
     * 修改密码
     * @return
     */
    @PostMapping(value = {"/updatePwd"}, produces = {MediaType.APPLICATION_JSON_VALUE}, consumes = {MediaType.APPLICATION_JSON_VALUE})
    @Log(title = "修改密码", businessType = BusinessType.APP_STUDENT, operatorType = OperatorType.MOBILE)
    public Result updatePwd(@Validated @RequestBody BaseReq<UpdatePwd> baseReq){
        return zzStudentManager.updatePwd(baseReq.getData());
    }
}
